package com.wy.OneClient.thread;

import com.wy.OneClient.Info;
import com.wy.OneClient.client;
import com.wy.OneClient.pojo.COMMAND;
import com.wy.OneClient.pojo.Data;
import com.wy.OneClient.pojo.DataType;
import com.wy.OneClient.pojo.Message;
import com.wy.OneClient.util.Utils;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author 吴宇~
 * @motto 我亦无他，唯手熟尔。
 * @edition jdk1.8
 * @reflection 0-1 喧闹任其喧闹，自由我自为之，我自风情万种，与世无争。
 * @date 2024/03/03/18:52
 * @target 心若有所向往，何惧道阻且长
 */

public class Receive extends Thread {
    private DatagramSocket datagramSocket;
    private Message message;

    public Receive(DatagramSocket datagramSocket, Message message) {
        this.message = message;
        this.datagramSocket = datagramSocket;
    }

    public Receive() {
    }

    @Override
    public void run() {
        init();
       Utils.commandPrintGreen("接收端准备完成~");
        while (client.notice) {
            try {
                Message message = Utils.receiveMessageServiceImpl(datagramSocket);
//                判断接受信息是什么并作相应的处理
                judgmentReceiveContent(message);
            } catch (SocketException socketException) {
                System.out.println("发现连接异常");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("接收端结束");
    }

    public void init() {
        Thread.currentThread().setName("receiveThread");
    }

    //    检查是否已经连接。并且重新设置标志位。
    public void checkConnectedOrNot(Message message) throws IOException {
        if (!message.getData().getDataType().equals(DataType.COMMAND)) {
            return;
        }
//        如果收到的信息是，对方要来连接
        String data = (String) message.getData().getData();
        if (data.equals(COMMAND.COMMAND_CONNECT_TARGET_MACHINE)) {
            this.message.setData(new Data<String>(COMMAND.COMMAND_TARGET_RECEIVES_CONNECT, DataType.COMMAND));
//           如果你给我发这么一个信息，就说明咱们是第一次连接，我就把这个信息给你发回去，以此来告诉你我接收到你的信息了。
            Utils.sendMessageServiceImpl(datagramSocket, this.message);
            client.connectFlag = true;
            client.virtualConnectFlag = true;
            System.out.println(message.getAddressInfo().getLocalAddressIp() + ":" + message.getAddressInfo().getLocalPort() + "\\" + message.getUser().getName() + " 连接成功！！");
            startConnectThread();
        } else if (data.equals(COMMAND.COMMAND_TARGET_RECEIVES_CONNECT)) {
            client.connectFlag = true;
            client.virtualConnectFlag = true;
            System.out.println(message.getAddressInfo().getLocalAddressIp() + ":" + message.getAddressInfo().getLocalPort() + "\\" + message.getUser().getName() + " 连接成功！！");
            startConnectThread();
        } else {
            client.connectFlag = false;
        }
    }

    //    判断接受内容
    public void judgmentReceiveContent(Message message) throws IOException {

        switch (message.getData().getDataType()) {
            case COMMAND:
                if (!client.connectFlag) {
                    checkConnectedOrNot(message);
                    return;
                }
                handleCommand(message);
                break;
            case STRING:
                String data = (String) message.getData().getData();
                Utils.commandPrintRed(message.getUser().getName() + " (" + Utils.getCurrentTime() + ") : " + data);
                break;
            case FILE:
                System.out.println("开始接受文件..");
                byte[] bytes = (byte[])message.getData().getData();
                FileOutputStream fileOutputStream = new FileOutputStream(new File(Info.DEFAULT_ACCEPT_FILE+"\\1.jpg"));
                fileOutputStream.write(bytes);
                fileOutputStream.close();
                break;
            default:
                System.out.println("暂时不会走到这儿");
        }
    }


    public void startConnectThread() {
        new Thread(new ConnectSend(this.datagramSocket, this.message)).start();
    }

    public void handleCommand(Message message) throws IOException {
        String commandData = (String) message.getData().getData();
        switch (commandData) {
            case COMMAND.COMMAND_CLOSE:
                System.out.println(message.getAddressInfo().getLocalAddressIp() + ":" + message.getAddressInfo().getLocalPort() + "-" + "断开连接");
                // 然后发送一个消息给发送端，它就会再运行一次代码， 关闭线程,就将对面发送的信息发送回去。
                this.message.setData(new Data<String>(COMMAND.COMMAND_CLOSE, DataType.COMMAND));
                Utils.sendMessageServiceImpl(datagramSocket, this.message);
                client.connectFlag = false;  //表示断开连接了
//                如果收到一个close的信息。直接关闭虚拟线程，不能等它休眠的。
                client.virtualConnectFlag = false;
                Thread[] allThreads = new Thread[Thread.activeCount()];
                Thread.enumerate(allThreads);
                for (Thread thread : allThreads) {
                    if (thread != null && thread.getName().equals("connectThread")) {
                        thread.interrupt(); // 中断线程的休眠状态
                        break;
                    }
                }
                break;
            case COMMAND.COMMAND_TO_CLOSE:
                client.notice = false;
                client.connectFlag = false;  //表示断开连接了
                datagramSocket.close();
                break;
            case Info.CONNECTING:
                client.virtualConnectFlag = true;
                break;
            case COMMAND.COMMAND_REQUEST_SEND_FILE:
//                TODO: 发送一个同意发送文件  开启一个什么东西  开一个线程接收文件吧！！！
                System.out.println("开始接收文件");
            default:
                System.out.println("应该不会走到这儿");

        }
    }
}
